package com.wowangz.cms.topic.news.api;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.gson.Gson;
import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.common.utils.SysConstant.NewsBusinessstatus;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.topic.column.entity.Column;
import com.wowangz.cms.topic.column.service.ColumnService;
import com.wowangz.cms.topic.column.tree.ColumnTree;
import com.wowangz.cms.topic.news.entity.News;
import com.wowangz.cms.topic.news.service.NewsService;

@Controller
@Scope("prototype")
public class NewsController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(NewsController.class);

	/**
	 * 删除新闻内容信息
	 *
	 * @param request
	 * @param news
	 * @param response
	 */
	@RequestMapping(value = "/topic/news/deleteNews.json", method = RequestMethod.GET)
	public void deleteNews(HttpServletRequest request, News news, HttpServletResponse response) {
		AjaxDataEntity entity = new AjaxDataEntity();
		try {
			NewsService newsService = (NewsService) IssTransactionContainer.getInstance(NewsService.class, false);
			news.setModifytime(new Date());
			// 将新闻信息的状态改为无效状态，即删除
			news.setStatusid(SysConstant.RecordStatus.INVALID);
			news.setModifytime(new Date());
			news.setModifyuserid(getUserContext().getLoginUser().getId());
			newsService.updateNews(news);
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
		} catch (ServiceException e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private DataResult getDataResult(HttpServletRequest request, PangingParam pangingParam, Map<String, Object> paramMap) throws Exception {
		paramMap.put("statusid", SysConstant.RecordStatus.VALID);
		NewsService newsService = (NewsService) IssTransactionContainer.getInstance(NewsService.class, false);
		long resultCount = newsService.findNewsCountByMap(paramMap);
		List<News> news = newsService.findNewsPageByMap(paramMap);
		DataStyle dataStyle = new DataStyle();
		dataStyle.setPageIndex(pangingParam.getPage());
		dataStyle.setDataCount(resultCount);
		dataStyle.setDataList(news);
		dataStyle.addDepict("columnid", DataTypeConstant.LONG);// 栏目ID
		dataStyle.addDepict("publishstatus", DataTypeConstant.LONG);// 发布状态
		dataStyle.addDepict("newscode", DataTypeConstant.STRING);// 栏目名称
		dataStyle.addDepict("columnname", DataTypeConstant.STRING);// 栏目名称
		dataStyle.addDepict("title", DataTypeConstant.STRING);// 新闻内容标题
		dataStyle.addDepict("contents", DataTypeConstant.STRING);// 新闻内容
		dataStyle.addDepictByFunction("businessstatus", SysConstant.NewsBusinessstatus.class, "getName", new Class[] { long.class });// 发布状态
		dataStyle.addDepictByFunction("statusid", SysConstant.RecordStatus.class, "getName", new Class[] { long.class });// 状态
		dataStyle.addDepict("id", DataTypeConstant.LONG);
		DataResult dataResult = PangingTools.buildResultPagerInfo(dataStyle);
		return dataResult;
	}

	/**
	 * 新闻内容符合
	 *
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/topic/news/getNewsApprovalJson.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void getNewsApprovalJson(HttpServletRequest request, HttpServletResponse response) {
		try {
			PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			Map<String, Object> map = ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			if (StringUtils.isNotEmpty(request.getParameter("parentcolumn"))) {
				map.put("columnid", request.getParameter("parentcolumn"));
			}
			map.put("businessstatus", NewsBusinessstatus.DRAFT);
			DataResult dataResult = getDataResult(request, pangingParam, map);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/topic/news/getNewsJson.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void getNewsJson(HttpServletRequest request, HttpServletResponse response) {
		try {
			PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			Map<String, Object> map = ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			if (StringUtils.isNotEmpty(request.getParameter("parentcolumn"))) {
				map.put("columnid", request.getParameter("parentcolumn"));
			}
			DataResult dataResult = getDataResult(request, pangingParam, map);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发布新闻内容信息
	 *
	 * @param request
	 * @param news
	 * @param response
	 */
	@RequestMapping(value = "/topic/news/publistNews.json", method = RequestMethod.GET)
	public void publistNews(HttpServletRequest request, News news, HttpServletResponse response) {
		AjaxDataEntity entity = new AjaxDataEntity();
		try {
			NewsService newsService = (NewsService) IssTransactionContainer.getInstance(NewsService.class, false);
			news.setModifytime(new Date());
			// 将新闻信息的状态改为无效状态，即删除
			news.setBusinessstatus(NewsBusinessstatus.PUBLISHED);
			// 发布人
			news.setPublishers(getUserContext().getLoginUser().getId());
			// 修改人
			news.setModifyuserid(getUserContext().getLoginUser().getId());
			// 修改时间
			news.setModifytime(new Date());
			newsService.updateNews(news);
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert28"));
		} catch (ServiceException e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert29"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获得新闻列表
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/topic/news/queryNewsList.web", method = { RequestMethod.GET })
	public String queryNewsList(HttpServletRequest request, Model model) {
		ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
		Map<String, Object> map = new HashMap<String, Object>();
		// 获得所有的栏目信息
		List<Column> list = columnService.findAllColumnByMap(map);
		List<ColumnTree> columnTrees = new ArrayList<ColumnTree>();
		for (Column column : list) {
			columnTrees.add(new ColumnTree(column));
		}
		logger.info(new Gson().toJson(columnTrees));
		model.addAttribute("treeJson", new Gson().toJson(columnTrees));
		return "/WEB-INF/jsp/topic/news/newsList";
	}

	/**
	 * 保存新闻内容
	 *
	 * @param request
	 * @param news
	 * @param response
	 */
	@RequestMapping(value = "/topic/news/saveNews.json", method = RequestMethod.POST)
	public void saveNews(HttpServletRequest request, News news, HttpServletResponse response) {
		AjaxDataEntity entity = new AjaxDataEntity();
		try {
			NewsService newsService = (NewsService) IssTransactionContainer.getInstance(NewsService.class, false);
			String parentcolumn = request.getParameter("parentcolumn");
			if (StringUtils.isNotEmpty(parentcolumn)) {
				news.setColumnid(Long.valueOf(parentcolumn));
			}
			news.setInputtime(new Date());
			news.setBusinessstatus(SysConstant.NewsBusinessstatus.DRAFT);
			news.setStatusid(SysConstant.RecordStatus.VALID);
			news.setInputuserid(getUserContext().getLoginUser().getId());
			news.setModifytime(new Date());
			news.setModifyuserid(getUserContext().getLoginUser().getId());
			newsService.saveNews(news);
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
		} catch (ServiceException e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/topic/news/toNewsAdd.web")
	public String toNewsAdd(HttpServletRequest request, Model model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		model.addAttribute("newscode", "TN" + sdf.format(new Date()));
		ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
		Map<String, Object> map = new HashMap<String, Object>();
		// 获得所有的栏目信息
		List<Column> list = columnService.findAllColumnByMap(map);
		List<ColumnTree> columnTrees = new ArrayList<ColumnTree>();
		for (Column column : list) {
			columnTrees.add(new ColumnTree(column));
		}
		model.addAttribute("treeJson", new Gson().toJson(columnTrees));
		return "/WEB-INF/jsp/topic/news/newsAdd";
	}

	@RequestMapping(value = "/topic/news/toNewsEdit.web", method = { RequestMethod.GET })
	public String toNewsEdit(HttpServletRequest request, Model model) {
		try {
			ColumnService columnService = (ColumnService) IssTransactionContainer.getInstance(ColumnService.class, false);
			Map<String, Object> map = new HashMap<String, Object>();
			// 获得所有的栏目信息
			List<Column> list = columnService.findAllColumnByMap(map);
			List<ColumnTree> columnTrees = new ArrayList<ColumnTree>();
			for (Column column : list) {
				columnTrees.add(new ColumnTree(column));
			}
			logger.info(new Gson().toJson(columnTrees));
			model.addAttribute("treeJson", new Gson().toJson(columnTrees));
			NewsService newsService = (NewsService) IssTransactionContainer.getInstance(NewsService.class, false);
			String id = request.getParameter("id");
			if (StringUtils.isNotEmpty(id)) {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("id", id);
				News news = newsService.findOneNewsByMap(paramMap);
				model.addAttribute("news", news);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/topic/news/newsUpdate";
	}

	@RequestMapping(value = "/topic/news/toNewsView.web", method = { RequestMethod.GET })
	public String toNewsView(HttpServletRequest request, Model model) {
		try {
			NewsService newsService = (NewsService) IssTransactionContainer.getInstance(NewsService.class, false);
			String id = request.getParameter("id");
			if (StringUtils.isNotEmpty(id)) {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("id", id);
				News news = newsService.findOneNewsByMap(paramMap);
				model.addAttribute("news", news);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/topic/news/newsView";
	}

	/**
	 * 修改新闻内容信息
	 *
	 * @param request
	 * @param news
	 * @param response
	 */
	@RequestMapping(value = "/topic/news/updateNews.json", method = RequestMethod.POST)
	public void updateNews(HttpServletRequest request, News news, HttpServletResponse response) {
		AjaxDataEntity entity = new AjaxDataEntity();
		try {
			NewsService newsService = (NewsService) IssTransactionContainer.getInstance(NewsService.class, false);
			String parentcolumn = request.getParameter("parentcolumn");
			if (StringUtils.isNotEmpty(parentcolumn)) {
				news.setColumnid(Long.valueOf(parentcolumn));
			}
			news.setBusinessstatus(SysConstant.NewsBusinessstatus.DRAFT);
			news.setModifytime(new Date());
			news.setModifyuserid(getUserContext().getLoginUser().getId());
			newsService.updateNews(news);
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
		} catch (ServiceException e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert7"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
